import json

from django.db import transaction
from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from rest_framework.views import APIView
from allmodels.models import SysDict, SysDictItem  # 假设字典类型模型在 allmodels 中
from django.core.paginator import Paginator
from django.db.models import Q
from login.views import verify_token  # 假设已经有验证 token 的函数


class DictTypePageView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取查询参数
        keywords = request.GET.get('keywords', '')
        page_num = int(request.GET.get('pageNum', 1))
        page_size = int(request.GET.get('pageSize', 10))

        # 构建查询条件
        filters = Q()
        if keywords:
            filters &= Q(name__icontains=keywords) | Q(code__icontains=keywords)

        # 查询字典类型
        dict_types_query = SysDict.objects.filter(filters).order_by('id')
        paginator = Paginator(dict_types_query, page_size)
        dict_types_page = paginator.get_page(page_num)

        # 构建返回的数据结构
        dict_type_list = []
        for dict_type in dict_types_page:
            dict_type_list.append({
                "id": dict_type.id,
                "name": dict_type.name,
                "code": dict_type.code,
                # 如果status为true则返回1反之0
                "status": 1 if dict_type.status else 0,
            })

        # 返回分页数据
        return JsonResponse({
            "code": "00000",
            "data": {
                "list": dict_type_list,
                "total": paginator.count
            },
            "msg": "一切ok"
        })


class DictTypeFormView(APIView):
    def get(self, request, id, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 根据字典类型ID获取字典信息
            dict_type = SysDict.objects.get(id=id)

            # 返回字典类型表单数据
            return JsonResponse({
                'code': '00000',
                'data': {
                    'id': dict_type.id,
                    'name': dict_type.name,
                    'code': dict_type.code,
                    # 如果status为true则返回1反之0
                    "status": 1 if dict_type.status else 0,
                    'remark': dict_type.remark
                },
                'msg': '操作成功'
            })

        except SysDict.DoesNotExist:
            return JsonResponse({
                'code': '10006',
                'msg': '字典类型不存在'
            }, status=404)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)


class CreateDictTypeView(APIView):
    def post(self, request, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 解析请求体
            data = json.loads(request.body)

            # 验证必填参数
            if 'name' not in data or 'code' not in data:
                return JsonResponse({
                    'code': '10006',
                    'msg': '类型名称和编码为必填项'
                }, status=400)

            # 创建字典类型
            with transaction.atomic():
                dict_type = SysDict.objects.create(
                    name=data.get('name'),
                    code=data.get('code'),
                    status=data.get('status', 1),  # 默认为启用状态
                    remark=data.get('remark', '')
                )

            return JsonResponse({
                'code': '00000',
                'data': {
                    'id': dict_type.id,
                    'name': dict_type.name,
                    'code': dict_type.code,
                    'status': dict_type.status,
                    'remark': dict_type.remark
                },
                'msg': '字典类型创建成功'
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class UpdateDictTypeView(APIView):
    def put(self, request, id, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 获取请求中的 JSON 数据
            data = json.loads(request.body)

            # 查找字典类型，如果不存在则返回错误
            try:
                dict_type = SysDict.objects.get(id=id)
            except SysDict.DoesNotExist:
                return JsonResponse({
                    'code': '10006',
                    'msg': '字典类型不存在'
                }, status=404)

            # 更新字典类型的字段
            dict_type.name = data.get('name', dict_type.name)
            dict_type.code = data.get('code', dict_type.code)
            dict_type.status = data.get('status', dict_type.status)
            dict_type.remark = data.get('remark', dict_type.remark)
            dict_type.save()

            return JsonResponse({
                'code': '00000',
                'msg': '字典类型更新成功',
                'data': {
                    'id': dict_type.id,
                    'name': dict_type.name,
                    'code': dict_type.code,
                    'status': dict_type.status,
                    'remark': dict_type.remark
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class DeleteDictTypeView(APIView):
    def delete(self, request, ids, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 将传递的 ids 字符串转换为列表
            id_list = ids.split(',')

            # 在事务中执行删除操作
            with transaction.atomic():
                SysDict.objects.filter(id__in=id_list).delete()

            return JsonResponse({
                'code': '00000',
                'msg': '字典类型删除成功',
                'data': {}
            })

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class DictPageView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取查询参数
        keywords = request.GET.get('keywords', '')
        type_code = request.GET.get('typeCode', '')
        page_num = int(request.GET.get('pageNum', 1))
        page_size = int(request.GET.get('pageSize', 10))

        # 构建查询条件
        filters = Q()
        if keywords:
            filters &= Q(name__icontains=keywords) | Q(code__icontains=keywords)

        if type_code:
            filters &= Q(code=type_code)

        # 查询字典类型
        dict_query = SysDict.objects.filter(filters, is_deleted=False).order_by('id')
        paginator = Paginator(dict_query, page_size)
        dict_page = paginator.get_page(page_num)

        # 构建返回的数据结构
        dict_list = []
        for dict_type in dict_page:
            # 查询字典项
            dict_items = SysDictItem.objects.filter(dict_id=dict_type.id, status=True)
            dict_items_list = [
                {
                    "id": item.id,
                    "name": item.name,
                    "value": item.value,
                    "sort": item.sort,
                    # 如果status为true则返回1反之0
                    "status": 1 if item.status else 0,
                }
                for item in dict_items
            ]
            dict_list.append({
                "id": dict_type.id,
                "name": dict_type.name,
                "code": dict_type.code,
                # 如果status为true则返回1反之0
                "status": 1 if dict_type.status else 0,
                "dictItems": dict_items_list
            })

        # 返回分页数据
        return JsonResponse({
            "code": "00000",
            "data": {
                "list": dict_list,
                "total": paginator.count
            },
            "msg": "一切ok"
        })

class DictOptionsView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取查询参数
        type_code = request.GET.get('typeCode', '')
        if not type_code:
            return JsonResponse({
                'code': '10006',
                'msg': '字典类型编码是必填项'
            }, status=400)

        # 查询字典类型
        try:
            dict_type = SysDict.objects.get(code=type_code, is_deleted=False)
        except SysDict.DoesNotExist:
            return JsonResponse({
                'code': '10007',
                'msg': '字典类型不存在'
            }, status=404)

        # 查询字典项
        dict_items = SysDictItem.objects.filter(dict_id=dict_type.id, status=True).order_by('sort')
        dict_options = [
            {
                "value": item.value,
                "label": item.name
            }
            for item in dict_items
        ]

        # 返回数据
        return JsonResponse({
            "code": "00000",
            "data": dict_options,
            "msg": "操作成功"
        })

class DictFormView(APIView):
    def get(self, request, id, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 查询字典类型
        try:
            dict_type = SysDict.objects.get(id=id, is_deleted=False)
        except SysDict.DoesNotExist:
            return JsonResponse({
                'code': '10007',
                'msg': '字典类型不存在'
            }, status=404)

        # 查询字典项
        dict_items = SysDictItem.objects.filter(dict_id=dict_type.id, status=True).order_by('sort')
        dict_items_data = [
            {
                "id": item.id,
                "name": item.name,
                "value": item.value,
                "sort": item.sort,
                "status": item.status
            }
            for item in dict_items
        ]

        # 构建返回数据
        dict_data = {
            "id": dict_type.id,
            "name": dict_type.name,
            "code": dict_type.code,
            "status": dict_type.status,
            "dictItems": dict_items_data
        }

        # 返回数据
        return JsonResponse({
            "code": "00000",
            "data": dict_data,
            "msg": "一切ok"
        })

class CreateDictView(APIView):
    def post(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 解析请求体
            data = json.loads(request.body)

            # 验证必填参数
            if 'name' not in data or 'code' not in data:
                return JsonResponse({
                    'code': '10006',
                    'msg': '字典名称和编码为必填项'
                }, status=400)

            # 在事务中创建字典及其字典项
            with transaction.atomic():
                # 创建字典
                dict_obj = SysDict.objects.create(
                    name=data['name'],
                    code=data['code'],
                    status=data.get('status', 1),  # 默认为启用
                    remark=data.get('remark', '')
                )

                # 创建字典项
                dict_items = data.get('dictItems', [])
                for item in dict_items:
                    SysDictItem.objects.create(
                        dict_id=dict_obj.id,
                        name=item['name'],
                        value=item['value'],
                        sort=item.get('sort', 0),
                        status=item.get('status', 1),
                        remark=item.get('remark', '')
                    )

            return JsonResponse({
                'code': '00000',
                'msg': '字典创建成功',
                'data': {
                    'id': dict_obj.id,
                    'name': dict_obj.name,
                    'code': dict_obj.code,
                    'status': dict_obj.status,
                    'dictItems': dict_items
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class UpdateDictView(APIView):
    def put(self, request, id, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 解析请求体
            data = json.loads(request.body)

            # 查找字典，如果不存在则返回错误
            try:
                dict_obj = SysDict.objects.get(id=id)
            except SysDict.DoesNotExist:
                return JsonResponse({
                    'code': '10006',
                    'msg': '字典不存在'
                }, status=404)

            # 更新字典基本信息
            dict_obj.name = data.get('name', dict_obj.name)
            dict_obj.code = data.get('code', dict_obj.code)
            dict_obj.status = data.get('status', dict_obj.status)
            dict_obj.remark = data.get('remark', dict_obj.remark)
            dict_obj.save()

            # 更新字典项信息
            dict_items = data.get('dictItems', [])
            with transaction.atomic():
                # 删除现有字典项
                SysDictItem.objects.filter(dict_id=id).delete()

                # 插入新的字典项
                for item in dict_items:
                    SysDictItem.objects.create(
                        dict_id=dict_obj.id,
                        name=item['name'],
                        value=item['value'],
                        sort=item.get('sort', 0),
                        status=item.get('status', 1),
                        remark=item.get('remark', '')
                    )

            return JsonResponse({
                'code': '00000',
                'msg': '字典更新成功',
                'data': {
                    'id': dict_obj.id,
                    'name': dict_obj.name,
                    'code': dict_obj.code,
                    'status': dict_obj.status,
                    'dictItems': dict_items
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': '10007',
                'msg': '请求体格式错误'
            }, status=400)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class DeleteDictView(APIView):
    def delete(self, request, ids, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 获取要删除的字典 ID，多个 ID 以逗号分隔
            dict_ids = ids.split(',')

            # 执行删除操作
            with transaction.atomic():
                SysDict.objects.filter(id__in=dict_ids).delete()

            return JsonResponse({
                'code': '00000',
                'msg': '字典删除成功',
                'data': {}
            })

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class DictOptionsView1(APIView):
    def get(self, request, code, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 根据字典编码查找字典
            dict_obj = SysDict.objects.filter(code=code).first()
            if not dict_obj:
                return JsonResponse({
                    'code': '10006',
                    'msg': '字典不存在'
                }, status=404)

            # 获取字典数据项列表
            dict_items = SysDictItem.objects.filter(dict_id=dict_obj.id, status=1).order_by('sort')

            # 构建返回的数据结构
            options = []
            for item in dict_items:
                options.append({
                    'value': item.id,
                    'label': item.name,
                    'children': []  # 假设字典项没有子级数据项
                })

            # 返回字典项列表
            return JsonResponse({
                'code': '00000',
                'data': options,
                'msg': '操作成功'
            })

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

class DictListView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 获取所有字典类型及其对应的字典项
            dict_list = SysDict.objects.filter(status=True).order_by('id')
            response_data = []

            for dict_obj in dict_list:
                dict_items = SysDictItem.objects.filter(dict_id=dict_obj.id, status=True).order_by('sort')
                children = []
                for item in dict_items:
                    children.append({
                        'value': item.value,
                        'label': item.name
                    })

                response_data.append({
                    'value': dict_obj.code,
                    'label': dict_obj.name,
                    'children': children
                })

            return JsonResponse({
                'code': '00000',
                'data': response_data,
                'msg': '操作成功'
            })

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)